package com.yjian.service;

import com.yjian.common.CodeMap;
import com.yjian.common.SDataResult;
import com.yjian.dao.bean.User;
import com.yjian.dao.mapper.UserMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * Created by xuxiaobao on 2017/9/30.
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Value("${user.screct.key}")
    private String screct;

    public Object checkUserAndPassword(String phone, String password) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword(DigestUtils.md5DigestAsHex((password+screct).getBytes()));
        user.initQuerySql(true,false,false,false);
        user = userMapper.checkUserAndPassword(user);
        if (user != null) {
            String token = Base64.encodeBase64String(user.getUid().getBytes());
            return SDataResult.success(token);
        }
        return new SDataResult(CodeMap.FAIL, "手机号或密码输入不正确");
    }

    @Transactional
    public Object register(String phone, String code, String password, String confirmPassword) {
        int isExistPhone = userMapper.isExistUserPhone(phone);
        if (isExistPhone > 0) {
            return new SDataResult(CodeMap.FAIL, "用户手机号已存在");
        }

        //判断短信验证码是否正确

        //验证密码是否一致
        if (!StringUtils.equals(password,confirmPassword)) {
            return new SDataResult(CodeMap.FAIL, "密码不一致");
        }

        //保存用户
        User user = new User();
        user.setUid(com.yjian.common.StringUtils.randomKey());
        user.setPhone(phone);
        user.setPassword(DigestUtils.md5DigestAsHex((password+screct).getBytes()));
        user.setCreateTime(new Date().getTime());

        int i = userMapper.saveUser(user);
        if (i <= 0) {
            return SDataResult.fail();
        }
        return SDataResult.success("ok");
    }
}
